import React, { Component } from "react";
import { GraphQLClient } from "graphql-request";
import LinearProgress from "@material-ui/core/LinearProgress";
import Chip from "@material-ui/core/Chip";
import withStyles from "@material-ui/core/styles/withStyles";
import green from "@material-ui/core/colors/green";
import grey from "@material-ui/core/colors/grey";
import settings from "../../settings";

const graphqlClient = new GraphQLClient(`${settings.Prisma.endpoint}`);

const styles = (theme) => ({
    chipGood: {
        backgroundColor: green[500],
        color: grey[50],
    },
});

class AccountStatusField extends Component {
    constructor(props) {
        super(props);
        this.state = {
            status: null,
        };
    }

    componentDidMount() {
        const { creditCode } = this.props.record;
        graphqlClient.request(`
            {
               account(where: {
                   creditCode: "${creditCode}"
               }){
                   id
               }
            }
        `).then((res) => { 
            if (res.account) this.setState({ status: true });
            else this.setState({ status: false });
        });
    }

    render() {
        const { classes } = this.props;
        return this.state.status === null ? <LinearProgress /> 
            : ( 
                this.state.status 
                    ? <Chip 
                        label={<span id="status">已注册到区块链</span>} 
                        className={classes.chipGood}
                    />
                    : <Chip 
                        label={<span id="status">未注册到区块链</span>} 
                    />
            ); 
    }
}

const AccountStatusFieldWithStyles = withStyles(styles)(AccountStatusField);

AccountStatusFieldWithStyles.defaultProps = {
    addLabel: true,
};

export default AccountStatusFieldWithStyles;
